/**
 * 配置管理模块
 * 统一管理应用配置
 */

const path = require('path');

class Config {
  constructor() {
    this.config = {
      // 服务器配置
      server: {
        port: parseInt(process.env.PORT) || 3000,
        host: process.env.HOST || 'localhost'
      },
      
      // WebSocket 配置
      websocket: {
        port: parseInt(process.env.WS_PORT) || 3001,
        pingInterval: parseInt(process.env.WS_PING_INTERVAL) || 30000, // 30秒
        pongTimeout: parseInt(process.env.WS_PONG_TIMEOUT) || 5000,    // 5秒
        maxConnections: parseInt(process.env.WS_MAX_CONNECTIONS) || 1000
      },
      
      // 消息配置
      message: {
        maxLength: parseInt(process.env.MSG_MAX_LENGTH) || 1000,
        historyLimit: parseInt(process.env.MSG_HISTORY_LIMIT) || 100,
        rateLimit: parseInt(process.env.MSG_RATE_LIMIT) || 10 // 每秒消息数
      },
      
      // 安全配置
      security: {
        enableCors: process.env.ENABLE_CORS === 'true',
        allowedOrigins: (process.env.ALLOWED_ORIGINS || '*').split(','),
        maxNicknameLength: parseInt(process.env.MAX_NICKNAME_LENGTH) || 20
      },
      
      // 日志配置
      logging: {
        level: process.env.LOG_LEVEL || 'info',
        enableFileLogging: process.env.ENABLE_FILE_LOGGING === 'true',
        logDir: process.env.LOG_DIR || path.join(process.cwd(), 'logs')
      },
      
      // 环境配置
      environment: process.env.NODE_ENV || 'development',
      
      // 静态文件配置
      static: {
        dir: process.env.STATIC_DIR || path.join(process.cwd(), 'public')
      }
    };
  }

  /**
   * 获取配置值
   */
  get(path, defaultValue = undefined) {
    const keys = path.split('.');
    let value = this.config;
    
    for (const key of keys) {
      if (value && typeof value === 'object' && key in value) {
        value = value[key];
      } else {
        return defaultValue;
      }
    }
    
    return value;
  }

  /**
   * 设置配置值
   */
  set(path, value) {
    const keys = path.split('.');
    const lastKey = keys.pop();
    let target = this.config;
    
    for (const key of keys) {
      if (!target[key] || typeof target[key] !== 'object') {
        target[key] = {};
      }
      target = target[key];
    }
    
    target[lastKey] = value;
  }

  /**
   * 获取所有配置
   */
  getAll() {
    return { ...this.config };
  }

  /**
   * 验证必要配置
   */
  validate() {
    const required = [
      'server.port',
      'websocket.port'
    ];
    
    const missing = [];
    
    for (const path of required) {
      if (this.get(path) === undefined) {
        missing.push(path);
      }
    }
    
    if (missing.length > 0) {
      throw new Error(`缺少必要配置: ${missing.join(', ')}`);
    }
    
    return true;
  }

  /**
   * 是否为开发环境
   */
  isDevelopment() {
    return this.get('environment') === 'development';
  }

  /**
   * 是否为生产环境
   */
  isProduction() {
    return this.get('environment') === 'production';
  }
}

// 创建单例实例
const config = new Config();

module.exports = config;